import django
import sqlite3
from django.core.mail import send_mail,send_mass_mail
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
import configparser

config = configparser.ConfigParser()

config.read("config.ini")
mail_host = config['email']['mail_host']
mail_user = config['email']['mail_user']
mail_pwd = config['email']['mail_pwd']
sender = config['email']['sender']


settings.configure(
    DEBUG = True,
    EMAIL_USE_SSL = True,
    EMAIL_HOST = mail_host,
    EMAIL_PORT = 465,
    EMAIL_HOST_USER = mail_user,
    EMAIL_HOST_PASSWORD = mail_pwd,
    DEFAULT_FROM_EMAIL = sender 
)

def send(receivers: list):
    subject = "The repository Keywords from gitee,github" 
    from_email, to = sender, receivers
    mail_msg = """
    <h3>开源代码网站关键词监控(gitee,github)</h3>
    <br>
    <br>
    <table border="1">
  <tr>
    <th>仓库地址</th>
    <th>查询关键词</th>
    <th>创建时间</th>
  </tr>
    """
    # 查询数据库
    conn = sqlite3.connect("project_info.db")
    cursor = conn.cursor()
    rows = cursor.execute("select * from project where notify_times < 3 ")
    msg_html = ""
    text_content = "开源代码网站关键词监控(gitee,github)\n"

    
    for row in rows:
        msg_html += f"<tr><td><a href='{row[0]}'>{row[0]}</a></td><td>{row[1]}</td><td>{row[2]}</td></tr>"
        text_content += f"仓库地址 ：{row[0]} 查询关键词：{row[1]} 创建时间：{row[2]}\n" 

    if msg_html == "":
        print("没有查询到新内容，不发送邮件通知")
        return 0

    mail_msg += msg_html + f'''</table>'''
    try:
        msg = EmailMultiAlternatives(subject, text_content, from_email, to)
        msg.attach_alternative(mail_msg, "text/html")
        msg.send()
        print(f"已发送邮件至 {';'.join(to)}，重复内容最多发送 3 次邮件")
        # 更新数据库()
        cursor.execute("update project set notify_times = notify_times+1 where notify_times < 3")
        conn.commit()
        conn.close()
    except Exception as e:
        print("Error: 无法发送邮件", e)